import logging
import allure
import pytest
from commons.kdt import KeyWord
from pytest_xlsx.file import XlsxItem


logger = logging.getLogger(__name__)


def pytest_xlsx_run_step(item: XlsxItem):
    if not hasattr(item, "kw"):
        item.kw = KeyWord(item.usefixtures)
        logger.info(f"本用例请求fuxtire如下：{list(item.usefixtures.keys())}")

    data = item.current_step

    key = data["关键字"]
    args = [data["参数"],]
    args.extend(data["_BlankField"])
    remark = data["步骤名"]

    logger.info(f"执行关键字: {key}, 参数: {args}")
    f = getattr(item.kw, key)
    if f is None:
        logger.error(f"关键字不存在: {key}")
        raise AttributeError(f"关键字不存在: {key}")

    f(*args)
    logger.info(f"关键字执行完毕 {key}")

    if item.kw.driver:
        png = item.kw.driver.get_screenshot_as_png()
        allure.attach(png, remark, allure.attachment_type.PNG)

    return 1


@pytest.fixture(scope="class")
def chrome():
    from selenium.webdriver import Chrome, ChromeOptions
    options = ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    options.add_argument('--disable-gpu')
    options.add_argument('--disable-dev-shm-usage')
    options.add_argument('--disable-site-isolation-trials')
    options.add_argument('--lang=zh-CN')
    options.add_argument('--window-size=1920,1080')
    driver = Chrome(options=options)

    yield driver

    driver.quit()
